import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/cash_flow_entity.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';
import 'package:nyh_motorcade_app/widgets/custom_app_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'cash_flow_controller.dart';
import 'cash_flow_filter/cash_flow_filter_page.dart';

class CashFlowPage extends StatelessWidget {
  final controller = Get.put(CashFlowController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.color_background,
      appBar: CustomAppBar(context: context, title: "资金流水"),
      body: GetBuilder<CashFlowController>(
        builder: (controller) {
          return Stack(
            children: [
              Column(
                children: [
                  buildFilterWidget(context),
                  buildListViewWidget(),
                ],
              ),
              Visibility(
                visible: controller.isShowFilterWidget,
                child: CashFlowFilterPage(
                  showAccountTransactionType: controller.sourceId.isEmpty,
                  onConfirm: (startDate, endDate, accountType, transactionType) {
                    if (controller.sourceId.isNotEmpty) {
                      controller.selectFilter(startDate, endDate, controller.accountType, controller.transactionType);
                    } else {
                      controller.selectFilter(startDate, endDate, accountType, transactionType);
                    }
                  },
                  onClose: () {
                    controller.isShowFilterWidget = false;
                    controller.update();
                  },
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget buildFilterWidget(BuildContext context) {
    return Container(
      height: 48.w,
      color: Colours.color_white,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          TextButton(
            onPressed: () {
              controller.selectWeek();
            },
            child: Text(
              "近一周",
              style: TextStyle(
                color: controller.isSelectWeek ? Colours.color_text_theme : Colours.color_9fa0ab,
                fontSize: controller.isSelectWeek ? 16.sp : 14.sp,
                fontWeight: controller.isSelectWeek ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            style: ButtonStyle(),
          ),
          TextButton(
            onPressed: () {
              controller.selectOneMonth();
            },
            child: Text(
              "近一月",
              style: TextStyle(
                color: controller.isSelectOneMonth ? Colours.color_text_theme : Colours.color_9fa0ab,
                fontSize: controller.isSelectOneMonth ? 16.sp : 14.sp,
                fontWeight: controller.isSelectOneMonth ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            style: ButtonStyle(),
          ),
          TextButton(
            onPressed: () {
              controller.selectThreeMonth();
            },
            child: Text(
              "近三月",
              style: TextStyle(
                color: controller.isSelectThreeMonth ? Colours.color_text_theme : Colours.color_9fa0ab,
                fontSize: controller.isSelectThreeMonth ? 16.sp : 14.sp,
                fontWeight: controller.isSelectThreeMonth ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            style: ButtonStyle(),
          ),
          TextButton(
            onPressed: () {
              controller.isShowFilterWidget = !controller.isShowFilterWidget;
              controller.update();
            },
            child: Text(
              "筛选",
              style: TextStyle(
                color: controller.isSelectFilter ? Colours.color_text_theme : Colours.color_9fa0ab,
                fontSize: controller.isSelectFilter ? 16.sp : 14.sp,
                fontWeight: controller.isSelectFilter ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            style: ButtonStyle(),
          ),
        ],
      ),
    );
  }

  Widget buildListViewWidget() {
    return Expanded(
      child: MultiStateWidget(
        child: SmartRefresher(
          controller: controller.refreshController,
          enablePullDown: true,
          enablePullUp: true,
          onRefresh: controller.onRefresh,
          onLoading: controller.onLoading,
          child: ListView.builder(
            physics: BouncingScrollPhysics(),
            shrinkWrap: true,
            controller: controller.scrollController,
            itemCount: controller.cashFlowList.length,
            itemBuilder: (context, index) {
              return buildItemWidget(index);
            },
          ),
        ),
        state: controller.multiState,
        onRetry: () {
          controller.onRetry();
        },
      ),
    );
  }

  Widget buildItemWidget(int index) {
    CashFlowItem cashFlowItem = controller.cashFlowList[index];
    String recordType = cashFlowItem.recordType ?? "";
    double amount = cashFlowItem.transAmount ?? 0.0;
    return Container(
      margin: EdgeInsets.only(left: 16.w, top: index == 0 ? 12.w : 0, right: 16.w, bottom: 12.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.w),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.w),
        child: Material(
          child: InkWell(
            onTap: () {
              Get.toNamed(Routes.cashFlowDetails, arguments: {
                Constant.PARAM_CASH_FLOW_ID: cashFlowItem.id ?? "",
                Constant.PARAM_CASH_FLOW_TYPE: recordType,
              });
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.w, horizontal: 16.w),
                  child: Row(
                    children: [
                      Image.asset(
                        "images/${getIconName(recordType)}.png",
                        fit: BoxFit.cover,
                        height: 42.w,
                        width: 42.w,
                      ),
                      SizedBox(
                        width: 16.w,
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  getTitle(recordType),
                                  style: TextStyle(
                                    color: Colours.color_text_theme,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                                Text(
                                  amount >= 0.0 ? "+${FormatUtils.formatMoney(amount)}" : FormatUtils.formatMoney(amount),
                                  style: TextStyle(
                                    color: amount >= 0.0 ? Colours.color_theme : Colours.color_text_theme,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 5.w,
                            ),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Image.asset("images/ic_date.png"),
                                SizedBox(
                                  width: 3.w,
                                ),
                                Text(
                                  cashFlowItem.operateTime ?? "",
                                  style: TextStyle(
                                    color: Colours.color_b1b2bb,
                                    fontSize: 12.sp,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(
                  color: Colours.color_background,
                  height: 1.w,
                  thickness: 1.w,
                ),
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 14.w, horizontal: 16.w),
                  child: buildItemContentWidget(cashFlowItem),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  String getIconName(String recordType) {
    switch (recordType) {
      case Constant.COMPANY_SETTLEMENT_OUT:
        return "ic_order_out";
      case Constant.COMPANY_SETTLEMENT_IN:
        return "ic_order_in";
      case Constant.ROLL_IN:
        return "ic_order_in";
      case Constant.ROLL_OUT:
        return "ic_order_out";
      case Constant.ORDER_PAYMENT:
        return "ic_order_payment";
      case Constant.OTHER:
        return "ic_order_cancel";
      case Constant.ACCOUNT_RECHARGE:
        return "ic_order_recharge";
      default:
        return "ic_order_out";
    }
  }

  String getTitle(String recordType) {
    switch (recordType) {
      case Constant.COMPANY_SETTLEMENT_OUT:
        return "公司付款";
      case Constant.COMPANY_SETTLEMENT_IN:
        return "公司收款";
      case Constant.ROLL_IN:
        return "金额拨入";
      case Constant.ROLL_OUT:
        return "金额拨出";
      case Constant.ORDER_PAYMENT:
        return "订单支付";
      case Constant.OTHER:
        return "订单作废";
      case Constant.ACCOUNT_RECHARGE:
        return "充值";
      default:
        return "公司付款";
    }
  }

  Widget buildItemContentWidget(CashFlowItem cashFlowItem) {
    String recordType = cashFlowItem.recordType ?? "";

    if (recordType == Constant.ACCOUNT_RECHARGE) {
      return Text(
        "余额(元) ${FormatUtils.formatMoney(cashFlowItem.afterTransAmount)}",
        style: TextStyle(color: Colours.color_6f7082, fontSize: 12.sp),
      );
    } else {
      String textOne = "";
      String textTwo = "";
      String name = cashFlowItem.name ?? "";
      String tradingAccount = cashFlowItem.tradingAccount ?? "";
      String stationName = cashFlowItem.stationName ?? "";
      String afterTransAmount = FormatUtils.formatMoney(cashFlowItem.afterTransAmount, unit: "元");
      String tradingAccountAfterTransAmount = FormatUtils.formatMoney(cashFlowItem.tradingAccountAfterTransAmount, unit: "元");

      switch (recordType) {
        case Constant.COMPANY_SETTLEMENT_OUT:
          textOne = "付款：$name 余额：$afterTransAmount";
          textTwo = "收款：$tradingAccount";
          break;
        case Constant.COMPANY_SETTLEMENT_IN:
          textOne = "收款：$name 余额：$afterTransAmount";
          textTwo = "付款：$tradingAccount";
          break;
        case Constant.ROLL_IN:
          textOne = "拨入：$name 余额：$afterTransAmount";
          textTwo = "拨出：$tradingAccount 余额：$tradingAccountAfterTransAmount";
          break;
        case Constant.ROLL_OUT:
          textOne = "拨出：$name 余额：$afterTransAmount";
          textTwo = "拨入：$tradingAccount 余额：$tradingAccountAfterTransAmount";
          break;
        case Constant.ORDER_PAYMENT:
          textOne = "付款：$name 余额：$afterTransAmount";
          textTwo = "油站：$stationName";
          break;
        case Constant.OTHER:
          textOne = "收款：$name 余额：$afterTransAmount";
          textTwo = "油站：$stationName";
          break;
        default:
      }
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            textOne,
            style: TextStyle(color: Colours.color_6f7082, fontSize: 12.sp),
          ),
          SizedBox(
            height: 1.w,
          ),
          Text(
            textTwo,
            style: TextStyle(color: Colours.color_6f7082, fontSize: 12.sp),
          ),
        ],
      );
    }
  }
}
